Index: crypto/openssl/crypto/asn1/tasn_dec.c
===================================================================
--- crypto/openssl/crypto/asn1/tasn_dec.c	(revision 280272)
+++ crypto/openssl/crypto/asn1/tasn_dec.c	(working copy)
@@ -127,22 +127,16 @@ unsigned long ASN1_tag2bit(int tag)
 
 ASN1_VALUE *ASN1_item_d2i(ASN1_VALUE **pval,
 		const unsigned char **in, long len, const ASN1_ITEM *it)
-{
+	{
 	ASN1_TLC c;
 	ASN1_VALUE *ptmpval = NULL;
+	if (!pval)
+		pval = &ptmpval;
 	asn1_tlc_clear_nc(&c);
-	if (pval && *pval && it->itype == ASN1_ITYPE_PRIMITIVE)
-		ptmpval = *pval;
-	if (ASN1_item_ex_d2i(&ptmpval, in, len, it, -1, 0, 0, &c) > 0) {
-		if (pval && it->itype != ASN1_ITYPE_PRIMITIVE) {
-			if (*pval)
-				ASN1_item_free(*pval, it);
-			*pval = ptmpval;
-		}
-		return ptmpval;
+	if (ASN1_item_ex_d2i(pval, in, len, it, -1, 0, 0, &c) > 0) 
+		return *pval;
+	return NULL;
 	}
-	return NULL;
-}
 
 int ASN1_template_d2i(ASN1_VALUE **pval,
 		const unsigned char **in, long len, const ASN1_TEMPLATE *tt)
Index: crypto/openssl/crypto/ec/ec_asn1.c
===================================================================
--- crypto/openssl/crypto/ec/ec_asn1.c	(revision 280272)
+++ crypto/openssl/crypto/ec/ec_asn1.c	(working copy)
@@ -1142,8 +1142,6 @@ EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigne
                                  ERR_R_MALLOC_FAILURE);
 			goto err;
 			}
-		if (a)
-			*a = ret;
 		}
 	else
 		ret = *a;
@@ -1225,11 +1223,13 @@ EC_KEY *d2i_ECPrivateKey(EC_KEY **a, const unsigne
 		ret->enc_flag |= EC_PKEY_NO_PUBKEY;
 		}
 
+	if (a)
+		*a = ret;
 	ok = 1;
 err:
 	if (!ok)
 		{
-		if (ret)
+		if (ret && (a == NULL || *a != ret))
 			EC_KEY_free(ret);
 		ret = NULL;
 		}
Index: crypto/openssl/crypto/x509/x509_req.c
===================================================================
--- crypto/openssl/crypto/x509/x509_req.c	(revision 280272)
+++ crypto/openssl/crypto/x509/x509_req.c	(working copy)
@@ -92,6 +92,8 @@ X509_REQ *X509_to_X509_REQ(X509 *x, EVP_PKEY *pkey
 		goto err;
 
 	pktmp = X509_get_pubkey(x);
+	if (pktmp == NULL)
+		goto err;
 	i=X509_REQ_set_pubkey(ret,pktmp);
 	EVP_PKEY_free(pktmp);
 	if (!i) goto err;
